package com.wy.framework.interceptors;

import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.wy.component.dataConvert.DateUtil;
import com.wy.component.redis.RedisUtil;
import com.wy.framework.adapter.MessageSourceAdapter;
import com.wy.framework.pojos.TSysUserinfo;

/**
 * 项目名称：openportal
 * 类名称：SessionAuthorityInterceptor
 * 类描述：Session判断拦截器
 * 创建人：张旭星
 * 创建时间：2015-12-28 下午3:34:54
 * 修改人：张旭星
 * 修改时间：2015-12-28 下午3:34:54
 * 版本信息：@version 1.0
 * Copyright (c) 2015万雍科技（上海）有限公司-版权所有  
 * 修改备注：
 * @version 
 */
public class SessionAuthorityInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = 1L;

	private static Logger logger = LoggerFactory
			.getLogger(SessionAuthorityInterceptor.class);

	@Autowired
	protected MessageSourceAdapter msgSourceAdapter;

	@SuppressWarnings("unchecked")
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		String uri = ServletActionContext.getRequest().getRequestURI();
		//不需要token即可执行
		if(StringUtils.contains("/apps/appManage/myListLoginLink,/apps/appManage/myListMarketNews,/manage/user/selfInfoLoad,/manage/user/judgePassExists,/service/news/myListMarketNews,/manage/user/info,appLogin,banner/show,content/search,heartbeat/getInfo,card/show,apps/list,apps/show,news/showThumbList,news/updateViews,service/showList,/login,/logout",uri)){
			return invocation.invoke();
		}
		
		String token = ServletActionContext.getRequest().getParameter("token");
		//无token
		if(StringUtils.isEmpty(token)){
//			ServletActionContext.getResponse().setStatus(402);
//			return "noRedis";
		}
		//有token
		else{
			String userId = RedisUtil.getUserId(token);
			if (StringUtils.isEmpty(userId)) {
				ServletActionContext.getResponse().setStatus(402);
				return "noRedis";
			}
			//重置生命周期
			else{
				RedisUtil.expire(token);
			}
			
			// 验证用户是否有权限
//			Set<String> userAction = tSysUserinfo.getActionSet();
//			if ((userAction == null || !userAction.contains(uri))) {
//				logger.error("用户没有{}的权限", uri);
//				ServletActionContext.getResponse().setStatus(403);
//				return "noPermission";
//			} else {
//				String currentUserAction = msgSourceAdapter.getMessage(uri);
//				if (!"".equals(currentUserAction)) {
//					logger.info(tSysUserinfo.getUserName() + " 在 '"
//							+ DateUtil.getCurrentDateTime() + "' 执行了' "
//							+ currentUserAction + "' 操作");
//				}
//			}
		}
		return invocation.invoke();
	}

	public String getActionFromUri(String uri) {
		if (uri.indexOf('/') >= 0) {
			int i = uri.lastIndexOf('/');
			return uri.substring(i + 1);
		}
		return uri;
	}
}
